﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Citi.Helpers;
using Citi.SecurityHelper;
using Citi.RoutineBase;

namespace Citi.GocAttributes.SchedulerUI
{
    public abstract class ImportFeed : RoutineBase.IExecutableRoutine
    {
        internal readonly string feedFolder = ConfigurationManager.AppSettings["FeedFolder"];
        internal readonly string proxy = ConfigurationManager.AppSettings["Proxy"];
        protected abstract string FileName { get; }
        protected abstract void Import(RoutineBase.ICurrentAction currentAction, DateTime referenceDate, string filePath);
        internal string robotUsername;
        internal string robotPassword;

        public IEnumerable<RoutineParameter> Parameters { get { return null; } }

        public void Rollback(ref RoutineBase.ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Start(DateTime scheduledDate, ref RoutineBase.ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            robotUsername = parameters["RobotUsername"].ToString();
            robotPassword = parameters["RobotPassword"].ToString();
            var referenceDate = new DateTime(scheduledDate.Year, scheduledDate.Month, 1);

            var filePath = FileName.ToLower().StartsWith("http")
                ? DownloadFeed(currentAction, referenceDate, parameters["SoeidResponsible"].ToString())
                : Path.Combine(feedFolder, string.Format(FileName, referenceDate.ToString("yyyyMM")));

            currentAction.Description = string.Format("Looking for file in folder {0}", feedFolder);

            var file = string.Concat(filePath, ".xls");
            currentAction.Description = string.Format("Looking for {0}", file);

            //using (NetworkShareAccesser.Access(filePath, robotUsername, robotPassword))
            //{
            //using (ImpersonateCitiUser.GetImpersonateUser("ND61955", robotUsername, robotPassword))
            //{
            if (File.Exists(file))
            {
                StartImport(currentAction, referenceDate, file);
                RedirectFileToImportedFolder(feedFolder, file);
                return;
            }

            file = string.Concat(filePath, ".xlsx");
            currentAction.Description = string.Format("Looking for {0}", file);

            if (File.Exists(file))
            {
                StartImport(currentAction, referenceDate, file);
                RedirectFileToImportedFolder(feedFolder, file);
            }
            else
                currentAction.Description = "No file was found. The routine was set as completed";
            //}
        }

        private string DownloadFeed(RoutineBase.ICurrentAction currentAction, DateTime referenceDate, string soeidResponsible)
        {
            string filePath;
            var fileDownloaded = Path.Combine(feedFolder, string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(FileName)
                , DateTime.Today.ToString("yyyyMMdd"), Path.GetExtension(FileName)));

            currentAction.Description = string.Format("Downloading feed to {0}", fileDownloaded);
            
            SecurityDownload.DownloadRemoteFile(FileName, fileDownloaded, soeidResponsible, proxy);

            var directoryToSave = Path.Combine(feedFolder, "Zips");
            if (!Directory.Exists(directoryToSave)) Directory.CreateDirectory(directoryToSave);

            currentAction.Description = "Decompressing files";
            FileHelper.Decompress(fileDownloaded, directoryToSave);
            File.Delete(fileDownloaded);

            filePath = Directory.GetFiles(directoryToSave).FirstOrDefault(x => Path.GetExtension(x) == ".xls" || Path.GetExtension(x) == ".xlsx");

            var newFileName = Path.Combine(Path.GetDirectoryName(filePath),
                string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(filePath), referenceDate.ToString("yyyyMM"), Path.GetExtension(filePath)));

            File.Copy(filePath, newFileName, true);
            File.Delete(filePath);
            filePath = newFileName.Replace(Path.GetExtension(filePath), string.Empty);
            
            return filePath;
        }

        private void RedirectFileToImportedFolder(string feedFolder, string file)
        {
            var directoryToSave = Path.Combine(feedFolder, "Imported");
            if (!Directory.Exists(directoryToSave)) Directory.CreateDirectory(directoryToSave);

            var movePath = Path.Combine(directoryToSave, Path.GetFileName(file));

            if (File.Exists(movePath))
                File.Delete(movePath);

            File.Move(file, movePath);
        }

        private void StartImport(RoutineBase.ICurrentAction currentAction, DateTime referenceDate, string filePath)
        {
            currentAction.Description = string.Format("Importing file: {0}", filePath);
            Import(currentAction, referenceDate, filePath);
            currentAction.Description = "File imported";
        }

        public void Stop(ref RoutineBase.ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }
    }
}